<template>
  <div>
    <el-form
      ref="formRef"
      :class="handleType == 'view' ? 'view' : ''"
      label-align="right"
      label-width="120"
      size="default"
      :label-position="handleType == 'view' ? 'left' : 'top'"
    >
      <template v-if="handleType == 'view'">
        <el-row :gutter="21">
          <el-col :span="6">
            <el-form-item label="产品状态:">{{ form.product_status_text }} </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售状态:">{{ form.sales_status_text }}</el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="货源状态:">{{ form.supply_status_text }} </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="智能清洁产品状态:" label-width="140">
              {{ is_classified ? form.clean_product_status_text : "--" }}</el-form-item
            >
          </el-col>

          <el-col :span="6">
            <el-form-item label="产品品牌:"
              >{{ form.goods_sku_sales_info.brand_name }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品类型:">{{
              form.sku_product_type_text
            }}</el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="辅料用途:">{{
              form.sku_product_type == 2 ? getAccessoriesUse(form.accessories_use) : "--"
            }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="插头规格:"
              >{{ form.goods_sku_sales_info.plug_specification_text }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="透明计划:">{{
              form.is_transparent_plan_text
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="样品采购类型:">{{
              getSamplePurchaseType(form.sample_purchase_type)
            }}</el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否全新件:"
              >{{ form.goods_sku_sales_info.is_new_product_text }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单品数:">{{ form.item_number }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否季节性产品:">{{
              form.goods_sku_sales_info.is_seasonal_product_text
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否已建模:">{{
              form.goods_sku_sales_info.is_build_model_text
            }}</el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="EAN码:">{{
              form.goods_sku_sales_info.ean_number
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品等级:"> {{ form.product_level }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否定制品:">
              {{ form.is_custom_product_text }}</el-form-item
            >
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否切换SKU:">
              {{ form.goods_sku_relation_old?.is_change_sku == 1 ? "是" : "否" }}
              <span v-if="form.goods_sku_relation_old?.goods_sku">
                SKU：{{
                  form.goods_sku_relation_old?.goods_sku ||
                  form.goods_sku_relation_old?.old_sku
                }}
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="认证类型:"> </el-form-item>
            <el-table border :data="form.goods_sku_authentication" size="mini">
              <el-table-column prop="country_name" label="认证国家">
                <template #default="{ row }">
                  {{ row.country.map((i) => i.country_name).join(",") }}
                </template>
              </el-table-column>
              <el-table-column prop="authentication_name" label="类型"></el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义规格:"> </el-form-item>
            <el-table
              border
              :data="form.goods_sku_sales_info.custom_specification"
              size="mini"
            >
              <el-table-column prop="name" label="规格"></el-table-column>
              <el-table-column prop="value" label="规格值"></el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <el-form-item label="热卖月份:"> </el-form-item>
            <el-table border :data="form.goods_sku_sell_month" size="mini">
              <el-table-column label="国家">
                <template #default="{ row }">
                  <span>{{ getCountryName(row.country) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="热卖月份">
                <template #default="{ row }">
                  <span>{{
                    formatMonth(row.hot_sell_start_month, row.hot_sell_end_month)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template #default="{ row }">
                  <span>{{ row.remark }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="12">
            <el-form-item label="禁售平台/站点:"> </el-form-item>
            <el-table border :data="form.goods_sku_prohibited_sales" size="mini">
              <el-table-column prop="platform_name" label="平台"></el-table-column>
              <el-table-column prop="site_code" label="站点"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <div class="w-[100%] flex flex-wrap">
          <el-form-item label="产品状态" class="w-120px">
            <template v-if="handleType == 'view'">
              {{ form.product_status_text }}
            </template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.product_status"
                :disabled="disabled || form?.dev_status == 4"
                @change="changeStatus($event, 'product_status')"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].productStatusText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="销售状态" class="w-120px">
            <template v-if="handleType == 'view'">
              {{ form.sales_status_text }}
            </template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.sales_status"
                :disabled="disabled || form?.dev_status == 4"
                @change="changeSalesStatus($event, 'sales_status')"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].salesStatusText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="货源状态" class="w-120px">
            <template v-if="handleType == 'view'">
              {{ form.supply_status_text }}
            </template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.supply_status"
                :disabled="disabled || form?.dev_status == 4"
                @change="changeStatus($event, 'supply_status')"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].supplyStatusText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="智能清洁产品状态" v-if="is_classified">
            <template #label>
              <div class="flex items-center">
                智能清洁产品状态
                <el-tooltip content="Top center" placement="top">
                  <template #content>
                    说明：<br />
                    1、新增SKU，若无变体状态=老品，则状态默认：新品；反之状态默认：老品；
                    <br />
                    2、新品满足连续销售六个月及以上，且无连续一个月（30）无销量情况，状态自动改为：老品；<br />
                    3、新品满足连续销售六个月及以上，且有连续一个月（30）无销量情况，此类修改会自动发起审批；<br />
                    审批通过则变更为老品；审批失败，则改为新品观察期； <br />
                    4、新品观察期，修改为老品；自动发起审批,审批通过则变更为老品；审批失败，则销售状态改为：清库；
                    <br />
                    5、老品状态不支持修改； <br />
                  </template>
                  <svg-icon icon-class="QuestionFilled"></svg-icon>
                </el-tooltip>
              </div>
            </template>
            <el-select
              class="w-full"
              v-model="form.clean_product_status"
              placeholder="智能清洁产品状态"
              filterable
              @change="changeCleanProduct"
              :disabled="is_classified_disabled"
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].cleanProductStatusText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品等级" class="w-120px">
            <template v-if="handleType == 'view'">
              {{ form.product_level }}
            </template>
            <template v-else>
              <el-select class="w-full" v-model="form.product_level" clearable disabled>
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].productLevelText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>
        </div>

        <div class="w-[100%] flex flex-wrap">
          <el-form-item label="产品品牌" :required="handleType != 'view'">
            <template v-if="handleType == 'view'">
              {{ form.goods_sku_sales_info.brand_name }}
            </template>
            <template v-else>
              <SelectBrand
                v-model="form.goods_sku_sales_info.brand_id"
                placeholder="请选择商品品牌"
                class="w-full"
                @changeName="changeBrandName"
                :disabled="disabled"
              >
              </SelectBrand>
            </template>
          </el-form-item>

          <el-form-item label="产品类型" class="w-120px">
            <template v-if="handleType == 'view'">
              {{ form.sku_product_type_text }}
            </template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.sku_product_type"
                :disabled="disabled || disabled_sku_product_type || handleType == 'edit'"
                @change="changeProductType"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].skuProductTypeText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="辅料用途" v-if="form.sku_product_type == 2">
            <template #label>
              <div class="flex items-center">
                辅料用途
                <el-tooltip content="Top center" placement="top">
                  <template #content>
                    采购入库：入库时将扣减对应辅料库存；物流发货、其他：发货时无需扣减库存；</template
                  >
                  <svg-icon icon-class="QuestionFilled"></svg-icon>
                </el-tooltip>
              </div>
            </template>
            <template v-if="handleType == 'view'">{{ form.accessories_use }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.accessories_use"
                :disabled="disabled"
                clearable
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].accessoriesUseText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="插头规格" class="w-250px">
            <template v-if="handleType == 'view'">{{
              form.goods_sku_sales_info.plug_specification_text
            }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.goods_sku_sales_info.plug_specification"
                collapse-tags
                placeholder="选择"
                clearable
                :disabled="disabled"
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0]
                    .plugSpecificationText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="透明计划" class="w-120px">
            <template v-if="handleType == 'view'">{{
              form.is_transparent_plan_text
            }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.is_transparent_plan"
                :disabled="disabled"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].transparentPlanText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="样品采购类型">
            <template v-if="handleType == 'view'">{{
              form.sample_purchase_type_text
            }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.sample_purchase_type"
                collapse-tags
                placeholder="选择"
                clearable
                :disabled="disabled"
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].samplePurchaseType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="是否全新件" class="w-140px">
            <template #label>
              <div class="flex items-center">
                是否全新件
                <el-tooltip content="Top center" placement="top">
                  <template #content>
                    用于ebay平台刊登时，判断Condition物品状态如何维护；是否全新品=否，则表示该SKU为翻新产品</template
                  >
                  <svg-icon icon-class="QuestionFilled"></svg-icon>
                </el-tooltip>
              </div>
            </template>
            <template v-if="handleType == 'view'">
              {{ form.goods_sku_sales_info.is_new_product }}</template
            >
            <template v-else>
              <el-radio-group
                v-model="form.goods_sku_sales_info.is_new_product"
                :disabled="disabled"
              >
                <el-radio
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0].isNewProductText"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-form-item>
        </div>

        <div class="w-[100%] flex flex-wrap">
          <el-form-item label="单品数">
            <template v-if="handleType == 'view'">{{ form.item_number }}</template>
            <template v-else>
              <el-input
                v-model="form.item_number"
                oninput="value=value.replace(/[^0-9]/g,'')"
                placeholder="请输入"
                :disabled="disabled"
              ></el-input>
            </template>
          </el-form-item>
          <el-form-item
            label="是否季节性产品"
            style="width: 125px"
            :required="handleType != 'view'"
          >
            <template v-if="handleType == 'view'">
              {{ form.goods_sku_sales_info.is_seasonal_product }}</template
            >
            <template v-else>
              <el-radio-group
                v-model="form.goods_sku_sales_info.is_seasonal_product"
                :disabled="disabled"
                @change="changeSeasonalProduct"
              >
                <el-radio
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0]
                    .isSeasonalProductText"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-form-item>
          <el-form-item label="是否已建模">
            <template v-if="handleType == 'view'">
              {{ form.goods_sku_sales_info.is_build_model_text }}</template
            >
            <el-select
              v-else
              class="w-full"
              v-model="form.goods_sku_sales_info.is_build_model"
              collapse-tags
              placeholder="选择"
              clearable
              :disabled="disabled"
            >
              <el-option
                v-for="item in options['goods.GoodsSkuSalesInfo']?.[0].isBuildModelText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="EAN码">
            <el-input
              v-model="form.goods_sku_sales_info.ean_number"
              placeholder="请输入"
              maxlength="13"
            />
          </el-form-item>
          <el-form-item label="是否定制品">
            <template #label>
              <div class="flex items-center">
                是否定制品
                <el-tooltip content="Top center" placement="top">
                  <template #content>
                    是否定制品说明<br />
                    1、定制品，用于商品和辅料之间的关系强绑定，保证商品和辅料成套发到客户手上<br />
                    2、PR、PO、头程、客户订单，在生成单据时均要强绑定物流发货类型的辅料<br
                  /></template>
                  <svg-icon icon-class="QuestionFilled"></svg-icon>
                </el-tooltip>
              </div>
            </template>
            <el-radio-group
              v-model="form.is_custom_product"
              :disabled="disabled"
              @change="changeSeasonalProduct"
            >
              <el-radio
                v-for="item in options['goods.GoodsSku']?.[0].isCustomProductText"
                :key="item.value"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            class="w-320px"
            label="是否切换SKU"
            v-if="form.sku_product_type == 1 && !form.disabled_relation"
          >
            <template #label>
              <div class="flex items-center">
                是否切换SKU
                <el-tooltip content="Top center" placement="top">
                  <template #content
                    ><div v-html="SWITCH_SKU_DESCRIPTION"></div
                  ></template>
                  <svg-icon icon-class="QuestionFilled"></svg-icon>
                </el-tooltip>
              </div>
            </template>
            <VGroup>
              <el-radio-group
                v-model="form.goods_sku_relation_old.is_change_sku"
                :disabled="disabled"
                @change="changeRelation"
              >
                <el-radio
                  v-for="item in skuRelationOptions"
                  :key="item.value"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>

              <el-input
                v-if="
                  form.goods_sku_relation_old.is_change_sku == 1 &&
                  form.goods_sku_relation_old.goods_sku
                "
                v-model="form.goods_sku_relation_old.old_sku"
                placeholder="输入旧SKU绑定"
                maxlength="20"
                style="width: 120px; margin-left: 6px"
                disabled
              />
              <template v-else>
                <el-input
                  v-show="form.goods_sku_relation_old.is_change_sku == 1"
                  v-model="form.goods_sku_relation_old.old_sku"
                  placeholder="输入旧SKU绑定"
                  maxlength="20"
                  style="width: 120px; margin-left: 6px"
                />
              </template>
            </VGroup>
          </el-form-item>
        </div>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item class="!w-[600px]" label="热卖月份" required>
              <template #label>
                <div class="inline-flex justify-between items-center w-[500px]">
                  <div>热卖月份</div>
                  <div class="flex items-center">
                    <el-button
                      class="mr-[16px]"
                      type="primary"
                      link
                      @click="resetArray('goods_sku_sell_month')"
                      >重置</el-button
                    >
                    <div
                      class="cursor-pointer text-[var(--base-placeholder-text-color)]"
                      @click="
                        handleMultipleColumnsAll(
                          'goods_sku_sell_month',
                          form.goods_sku_sell_month
                        )
                      "
                    >
                      更多（{{
                        form.goods_sku_sell_month.filter((i) => !i.delete).length
                      }}）>>
                    </div>
                  </div>
                </div>
              </template>
              <MultipleColumns
                v-model="form.goods_sku_sell_month"
                :disabled="disabled"
                type="goods_sku_sell_month"
              ></MultipleColumns>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <template v-if="handleType == 'view'">
              <div class="flex">
                <div class="text-sm text-gray-400 mr-2 mb-2">自定义规格</div>
                <div>
                  <div
                    class="col-style"
                    v-for="(item, index) in form.goods_sku_sales_info
                      .custom_specification"
                    :key="index"
                  >
                    {{ item.name }};{{ item.value }}
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <el-form-item label="自定义规格">
                <template #label>
                  <div class="inline-flex justify-between items-center w-[500px]">
                    <div>自定义规格</div>
                    <div class="flex items-center">
                      <el-button
                        class="mr-[16px]"
                        type="primary"
                        link
                        @click="resetArray('custom_specification')"
                        >重置</el-button
                      >
                      <div
                        class="cursor-pointer text-[var(--base-placeholder-text-color)]"
                        @click="
                          handleMultipleColumnsAll(
                            'custom_specification',
                            form.goods_sku_sales_info.custom_specification
                          )
                        "
                      >
                        更多（{{
                          form.goods_sku_sales_info.custom_specification.filter(
                            (i) => !i.delete
                          ).length
                        }}）>>
                      </div>
                    </div>
                  </div>
                </template>
                <MultipleColumns
                  v-model="form.goods_sku_sales_info.custom_specification"
                  :disabled="disabled"
                  type="custom_specification"
                ></MultipleColumns>
              </el-form-item>
            </template>
          </el-col>

          <el-col :span="10">
            <template v-if="handleType == 'view'">
              <div class="flex">
                <div class="text-sm text-gray-400 mr-2">认证类型</div>
                <div class="w-40">
                  <div
                    class="col-style"
                    v-for="(item, index) in form.goods_sku_authentication"
                    :key="index"
                  >
                    {{ item.country_name }}/ {{ item.authentication_name }}
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <el-form-item class="!w-[600px]" label="认证类型" required>
                <template #label>
                  <div class="inline-flex justify-between items-center w-[500px]">
                    <div>认证类型</div>
                    <div class="flex items-center">
                      <el-button
                        class="mr-[16px]"
                        type="primary"
                        link
                        @click="resetArray('goods_sku_authentication')"
                        >重置</el-button
                      >
                      <div
                        class="cursor-pointer text-[var(--base-placeholder-text-color)]"
                        @click="
                          handleMultipleColumnsAll(
                            'goods_sku_authentication',
                            form.goods_sku_authentication
                          )
                        "
                      >
                        更多（{{
                          form.goods_sku_authentication.filter((i) => !i.delete).length
                        }}）>>
                      </div>
                    </div>
                  </div>
                </template>
                <MultipleColumns
                  v-model="form.goods_sku_authentication"
                  :disabled="disabled"
                  type="goods_sku_authentication"
                ></MultipleColumns>
              </el-form-item>
            </template>
          </el-col>
          <el-col :span="12">
            <template v-if="handleType == 'view'">
              <div class="flex">
                <div class="text-sm text-gray-400 mr-2">禁售平台/站点</div>
                <div>
                  <div
                    class="col-style"
                    v-for="(item, index) in form.goods_sku_prohibited_sales"
                    :key="index"
                  >
                    {{ item.platform_name }};{{ item.site_name }}
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <el-form-item label="禁售平台/站点">
                <template #label>
                  <div class="inline-flex justify-between items-center w-[500px]">
                    <div>自定义规格</div>
                    <div class="flex items-center">
                      <el-button
                        class="mr-[16px]"
                        type="primary"
                        link
                        @click="resetArray('goods_sku_prohibited_sales')"
                        >重置</el-button
                      >
                      <div
                        class="cursor-pointer text-[var(--base-placeholder-text-color)]"
                        @click="
                          handleMultipleColumnsAll(
                            'goods_sku_prohibited_sales',
                            form.goods_sku_prohibited_sales
                          )
                        "
                      >
                        更多（{{
                          form.goods_sku_prohibited_sales.filter((i) => !i.delete).length
                        }}）>>
                      </div>
                    </div>
                  </div>
                </template>
                <MultipleColumns
                  v-model="form.goods_sku_prohibited_sales"
                  :disabled="disabled"
                  type="goods_sku_prohibited_sales"
                ></MultipleColumns>
              </el-form-item>
            </template>
          </el-col>
        </el-row>
      </template>
    </el-form>
  </div>
</template>

<script setup name="SellInfo">
import { reactive, inject } from "vue";
import SelectBrand from "@/components/SelectBrand";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import SelectCountry from "@/components/SelectCountry";
import { ElMessage, ElMessageBox } from "element-plus";
import { SKUCleanStatus, createClean } from "../api.js";
import { monthOptions } from "../data.js";
import { clean_classified } from "@/utils/product/data.js";
import { formatMonth } from "@/utils/index.js";
import SelectCountryV2 from "@/components/Selects/SelectCountryV2/index.vue";
import { SWITCH_SKU_DESCRIPTION } from "@/utils/product/data.js";

let options = reactive(inject("options"));
let handleType = reactive(inject("handleType"));
let formData = reactive(inject("form"));
let sku_product_type = reactive(inject("sku_product_type") || 1);

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/basic-info"))
  );
});

const disabled_sku_product_type = computed(() => {
  return sku_product_type.value;
});

// 是否智能清洁产品
const is_classified = ref(false);

watch(
  formData,
  (newVal, oldVal) => {
    is_classified.value = clean_classified.includes(
      newVal.spu_category ? newVal.spu_category[0] : ""
    );
  },
  { deep: true }
);

const is_classified_disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/basic-info")) ||
    form.value.old_clean_product_status == 2
  );
});

const formRef = ref();
const form = computed({
  get: () => {
    return props.modelValue || {};
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

// 增加一行
const add = (type) => {
  const obj = {
    custom_specification: {
      name: "",
      value: "",
    },
    goods_sku_authentication: {
      country: [],
      authentication_type: null,
    },
    goods_sku_prohibited_sales: {
      prohibited_platform: null,
      prohibited_site: null,
    },
    goods_sku_sell_month: {
      country_id: null,
    },
  };
  if (type == "custom_specification") {
    form.value.goods_sku_sales_info.custom_specification.push(obj[type]);
  } else {
    form.value[type].push(obj[type]);
  }
};
// 删除一行
const del = (index, type) => {
  if (type == "custom_specification") {
    form.value.goods_sku_sales_info.custom_specification[index].delete = 1;
  } else {
    form.value[type][index].delete = 1;
  }
};

const changePlatform = (val, index) => {
  form.value.goods_sku_prohibited_sales[index].platform_name = val;
};
const changeSite = (val, index) => {
  form.value.goods_sku_prohibited_sales[index].site_name = val;
};

const changeBrandName = (val) => {
  form.value.goods_sku_sales_info.brand_name = val;
};

const changeAuthentication = (val, row) => {
  const item = options.value["goods.GoodsSpu"]?.[0].authenticationText.find(
    (i) => i.value == val
  );
  row.authentication_name = item?.label;
};

const validate = () => {
  return new Promise((resolve, reject) => {
    formRef.value?.validate((valid, fields) => {
      if (valid) {
        resolve(true);
      } else {
        resolve(false);
      }
    });
  });
};
defineExpose({ validate });

const clean_map = new Map([
  [
    "need_change_order",
    "当前SKU有累计销售六个月及以上，且有连续一个月（30天）以上无销量情况，修改为老品需审批通过，点击确认将自动发起审批，审批后自动修改状态；是否继续操作？",
  ],
  ["disable", "当前SKU销量情况不满足变更为老品"],
  ["exist_change_order", "已存在变更单，不支持修改。"],
]);

const changeCleanProduct = (val, i) => {
  if (form.value.old_clean_product_status == 1 && val == 2) {
    SKUCleanStatus({
      sku_id: form.value.id,
      type: "new_to_old",
    }).then((res) => {
      if (res.data == "need_change_order") {
        ElMessageBox.confirm(clean_map.get(res.data))
          .then(async () => {
            try {
              await createClean({
                sku_id: form.value.id,
                type: 1,
                clean_product_status: val,
              });
              form.value.clean_product_status = form.value.old_clean_product_status;
            } catch (e) {
              throw Error(e);
            }
          })
          .catch(() => {
            form.value.clean_product_status = form.value.old_clean_product_status;
          });
      } else {
        ElMessage.error(clean_map.get(res.data));
        form.value.clean_product_status = form.value.old_clean_product_status;
      }
    });
  } else if (form.value.old_clean_product_status == 1 && val == 3) {
    ElMessageBox.confirm(
      "提示：无法直接修改为新品观察期，新品观察期只有修改为老品触发生成申请单，审批失败后会自动改为新品观察期；"
    )
      .then(() => {
        form.value.clean_product_status = form.value.old_clean_product_status;
      })
      .catch(() => {
        form.value.clean_product_status = form.value.old_clean_product_status;
      });
  } else if (form.value.old_clean_product_status == 3 && val == 2) {
    SKUCleanStatus({
      sku_id: form.value.id,
      type: "observe_to_old",
    }).then((res) => {
      if (res.data) {
        ElMessageBox.confirm(clean_map.get(res.data))
          .then(async () => {
            try {
              await createClean({
                sku_id: form.value.id,
                type: 2,
                clean_product_status: val,
              });
              form.value.clean_product_status = form.value.old_clean_product_status;
            } catch (e) {
              throw Error(e);
            }
          })
          .catch(() => {
            form.value.clean_product_status = form.value.old_clean_product_status;
          });
      }
    });
  } else if (form.value.old_clean_product_status == 3 && val == 1) {
    ElMessage.error("新品观察期不支持修改为新品，请知悉；");
    form.value.clean_product_status = form.value.old_clean_product_status;
  }
};

const keyMap = new Map([
  ["product_status", "spu_status"],
  ["sales_status", "spu_sales_status"],
  ["supply_status", "spu_supply_status"],
  ["clean_product_status", "spu_clean_product_status"],
]);
// SKU 修改状态触发SPU状态判断
const changeStatus = (val, key) => {
  const allKeysEqual = areAllValuesEqualTo(formData.value.goods_sku, key);
  if (allKeysEqual) {
    formData.value[keyMap.get(key)] = val;
    const allKeysEqual = areAllValuesEqualTo(formData.value.goods_sku, key);
    if (allKeysEqual) {
      formData.value[keyMap.get(key)] = val;
    }
  }
};

const areAllValuesEqualTo = (array, key) => {
  for (let i = 0; i < array.length - 1; i++) {
    if (array[i][key] !== array[i + 1][key]) {
      return false;
    }
  }
  return true;
};

// 切换产品类型 清空辅料用途
const changeProductType = () => {
  ElMessageBox.confirm("产品类型调整，系统将清空切换SKU。点击确认后执行?", "提示")
    .then(() => {
      form.value.old_sku_product_type = form.value.sku_product_type;
      form.value.goods_sku_relation_old.is_change_sku = 2;
      form.value.goods_sku_relation_old.old_sku = "";
    })
    .catch(() => {
      form.value.sku_product_type = form.value.old_sku_product_type;
    });
  form.value.accessories_use = "";
};

// 切换是否季节性产品 清空月份
const changeSeasonalProduct = () => {
  form.value.goods_sku_sales_info.season_month_start = "";
  form.value.goods_sku_sales_info.season_month_end = "";
};

// 修改销售状态
const changeSalesStatus = (val, key) => {
  if (form.value.inventory > 0 && val == 4) {
    ElMessageBox.confirm("该SKU的库存>0,是否继续改为停售？", "提示")
      .then(() => {
        form.value.sales_status = val;
        changeStatus(val, key);
      })
      .catch(() => {
        form.value.sales_status = form.value.old_sales_status;
        changeStatus(form.value.sales_status, key);
      });
  } else {
    changeStatus(val, key);
  }

  form.value.sales_status_text = getSalesStatus(val);
};

const getAccessoriesUse = (val) => {
  return options.value["goods.GoodsSku"]?.[0].accessoriesUseText.find(
    (i) => i.value == val
  )?.label;
};

const getSamplePurchaseType = (val) => {
  return options.value["goods.GoodsSku"]?.[0].samplePurchaseType.find(
    (i) => i.value == val
  )?.label;
};

const getCountryName = (list) => {
  return list.map((item) => item.country_name).join("、");
};

const getSalesStatus = (val) => {
  return options.value["goods.GoodsSku"]?.[0].salesStatusText.find((i) => i.value == val)
    ?.label;
};

// 重置数组
const resetArray = (type) => {
  ElMessageBox.confirm("是否清空当前数据？", "提示")
    .then(() => {
      const obj = {
        custom_specification: {
          name: "",
          value: "",
        },
        goods_sku_authentication: {
          country: [],
          authentication_type: null,
        },
        goods_sku_prohibited_sales: {
          platform_id: "",
          platform_name: "",
          site_code: "",
          site_name: "",
        },
        goods_sku_sell_month: {
          country: [],
          hot_sell_start_month: "",
          hot_sell_end_month: "",
          remark: "",
        },
      };
      if (handleType.value == "add") {
        if (type == "custom_specification") {
          form.value.goods_sku_sales_info.custom_specification = [obj[type]];
        } else {
          form.value[type] = [obj[type]];
        }
      } else {
        if (type == "custom_specification") {
          form.value.goods_sku_sales_info.custom_specification = form.value.goods_sku_sales_info.custom_specification.map(
            (item) => ({
              ...item,
              delete: 1,
            })
          );
          form.value.goods_sku_sales_info.custom_specification.push({
            ...obj[type],
          });
        } else {
          form.value[type] = form.value[type].map((item) => ({
            ...item,
            delete: 1,
          }));
          form.value[type].push({
            ...obj[type],
          });
        }
      }
    })
    .catch(() => {});
};

// 切换是否切换SKU
const skuRelationOptions = [
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 2,
  },
];

const changeRelation = (val) => {
  if (val == 1) {
    if (form.value.goods_sku_relation.length) {
      form.value.goods_sku_relation = form.value.goods_sku_relation.filter((item) => {
        if (item.id) {
          item.delete = 1; // 如果有 id，添加 delete 属性
          return true; // 保留该对象
        } else {
          return false; // 如果没有 id，过滤掉该对象
        }
      });
    }
    emit("changeGeneralactive");
  }
};

const emit = defineEmits(["changeGeneralactive"]);
</script>

<style lang="scss" scoped>
.bg-Fa {
  background: #f6faff;
  border-radius: 4px;
}

.view {
  .el-form-item {
    width: 100% !important;
  }
  .flex-wrap {
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
  }

  :deep(.el-form-item__label) {
    color: #999999;
    font-weight: 400;
  }
  :deep(.el-form-item__content) {
    display: inline-block;
    min-width: 60px;
  }
}

.col-style {
  background: #eaf3ff;
  border-radius: 16px;
  font-size: 14px;
  color: #3487ff;
  padding: 4px 12px;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.icon-color {
  color: #898989;
}

.el-form-item {
  width: 200px;
  &.w-120px {
    width: 120px;
  }
  &.w-320px {
    width: 320px;
  }
  &.w-450px {
    width: 450px;
  }
}
</style>
